import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Table, Button, Space, Tag, Select, Form, Drawer, List, Avatar, Typography, message, Divider, Pagination, Input, Tabs, Spin, Popconfirm, Switch } from 'antd';
import { ReloadOutlined, HistoryOutlined, EyeOutlined, MessageOutlined, GiftOutlined, DeleteOutlined, DownloadOutlined } from '@ant-design/icons';
import { useRooms } from '../hooks/useRooms';
import { useSessions, Session, SessionGiftSummary } from '../hooks/useSessions';
import { FixedSizeList as VirtualList, ListChildComponentProps } from 'react-window';
import type { FixedSizeList } from 'react-window';
import { API_ENDPOINTS } from '../constants/api';

const { Option } = Select;
const { Text } = Typography;

const DANMAKU_ITEM_HEIGHT = 76;

// 从视频文件名中提取真实录制时间，支持分段视频
const extractVideoStartTime = (filename: string): Date | null => {
  // 匹配格式：主播名_2025-01-10_14-30-00_000.flv 或 主播名_2025-01-10_14-30-00.flv
  const timePattern = /(\d{4}-\d{2}-\d{2})_(\d{2}-\d{2}-\d{2})(?:_(\d{3}))?/;
  const match = filename.match(timePattern);
  
  if (match && match[1] && match[2]) {
    const datePart = match[1];
    const timePart = match[2];
    const segmentNumber = match[3] ? parseInt(match[3], 10) : 0;
    
    // 转换格式：2025-01-10_14-30-00 -> 2025-01-10T14:30:00
    const isoString = `${datePart}T${timePart.replace(/-/g, ':')}`;
    const baseDate = new Date(isoString);
    
    if (isNaN(baseDate.getTime())) {
      return null;
    }
    
    // 如果是分段视频，计算实际开始时间
    // 假设每段30分钟（1800秒），根据分段号计算偏移
    if (segmentNumber > 0) {
      const segmentOffsetMs = segmentNumber * 30 * 60 * 1000; // 30分钟 * 分段号
      return new Date(baseDate.getTime() + segmentOffsetMs);
    }
    
    return baseDate;
  }
  
  return null;
};

// 格式化真实时间显示
const formatRealTime = (timestamp: Date) => {
  return timestamp.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit', 
    second: '2-digit' 
  });
};

// 保留原有的偏移量格式化函数作为备用
const formatOffset = (offsetMs: number) => {
  const totalSeconds = Math.max(0, Math.floor(offsetMs / 1000));
  const minutes = Math.floor(totalSeconds / 60);
  const seconds = totalSeconds % 60;
  const pad = (value: number) => value.toString().padStart(2, '0');
  return `${pad(minutes)}:${pad(seconds)}`;
};

const SessionsPage: React.FC = () => {
  const { rooms, fetchRooms } = useRooms();
  const { sessions, loading, fetchSessions, fetchSessionDetails, fetchSessionGiftStats, deleteSession } = useSessions();

  const [form] = Form.useForm();
  const [selectedRoomId, setSelectedRoomId] = useState<string | undefined>();
  const [detailsOpen, setDetailsOpen] = useState(false);
  const [detailsLoading, setDetailsLoading] = useState(false);
  const [currentDetails, setCurrentDetails] = useState<any | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(50);
  const [visibleTags, setVisibleTags] = useState<Set<string>>(new Set());
  const [currentSessionId, setCurrentSessionId] = useState<string | null>(null);
  const videoRef = useRef<HTMLVideoElement | null>(null);
  const fileInputRef = useRef<HTMLInputElement | null>(null);
  const playerContainerRef = useRef<HTMLDivElement | null>(null);
  const danmakuListRef = useRef<FixedSizeList | null>(null);
  const [videoSource, setVideoSource] = useState<string | null>(null);
  const [videoLabel, setVideoLabel] = useState<string>('');
  const [userUrl, setUserUrl] = useState('');
  const [currentTimeMs, setCurrentTimeMs] = useState(-1);
  const [visibleMessages, setVisibleMessages] = useState<any[]>([]);
  const [showDanmakuAvatar, setShowDanmakuAvatar] = useState(false);
  const nextMessageIndexRef = useRef(0);
  const previousTimeRef = useRef(-1);
  const objectUrlRef = useRef<string | null>(null);
  const [activeTab, setActiveTab] = useState('player');
  const [giftStats, setGiftStats] = useState<SessionGiftSummary | null>(null);
  const [giftStatsLoading, setGiftStatsLoading] = useState(false);
  const [windowHeight, setWindowHeight] = useState(window.innerHeight);
  const [giftStatsError, setGiftStatsError] = useState<string | null>(null);
  const [videoStartTime, setVideoStartTime] = useState<Date | null>(null);

  // 首次加载：拉取房间列表与所有会话
  useEffect(() => {
    fetchRooms();
    fetchSessions();
  }, []);

  // 监听窗口大小变化
  useEffect(() => {
    const handleResize = () => {
      setWindowHeight(window.innerHeight);
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);



  const handleRoomChange = async (roomId?: string) => {
    setSelectedRoomId(roomId);
    await fetchSessions(roomId);
  };

  const handleRefresh = async () => {
    await fetchSessions(selectedRoomId);
  };

  const handleDeleteSession = async (sessionId: string) => {
    const success = await deleteSession(sessionId);
    if (success) {
      if (currentSessionId === sessionId) {
        setDetailsOpen(false);
        setCurrentSessionId(null);
        setCurrentDetails(null);
        resetPlaybackState();
      }
    }
  };

  const loadGiftStats = async (sessionId: string) => {
    setGiftStatsLoading(true);
    setGiftStatsError(null);
    setGiftStats(null);
    try {
      const stats = await fetchSessionGiftStats(sessionId);
      setGiftStats(stats ?? null);
    } catch (error) {
      setGiftStatsError('获取礼物统计失败');
    } finally {
      setGiftStatsLoading(false);
    }
  };
  const calcDuration = (start?: string, end?: string | null) => {
    if (!start) return '-';
    if (!end) return '未知'; // 如果没有结束时间，显示未知
    const startMs = new Date(start).getTime();
    const endMs = new Date(end).getTime();
    if (Number.isNaN(startMs) || Number.isNaN(endMs)) return '-';
    const diff = Math.max(0, endMs - startMs);
    const mins = Math.floor(diff / 60000);
    const hours = Math.floor(mins / 60);
    const remainMins = mins % 60;
    return hours > 0 ? `${hours}h ${remainMins}m` : `${remainMins}m`;
  };

  const openDetails = async (sessionId: string) => {
    setDetailsOpen(true);
    setDetailsLoading(true);
    setCurrentPage(1); // 重置分页
    setVisibleTags(new Set()); // reset filters
    setCurrentSessionId(sessionId);
    void loadGiftStats(sessionId);
    try {
      const details = await fetchSessionDetails(sessionId);
      setCurrentDetails(details);
    } catch (e) {
      // 错误在hook中已提示
    } finally {
      setDetailsLoading(false);
    }
  };

  const columns = useMemo(() => [
    {
      title: 'Streamer',
      key: 'streamer',
      render: (record: Session) => record.room?.streamerName || '-'
    },
    {
      title: 'Session Title',
      dataIndex: 'title',
      key: 'title',
      render: (text?: string) => text || '-'
    },
    {
      title: 'Start Time',
      dataIndex: 'startTime',
      key: 'startTime',
      render: (value: string) => (value ? new Date(value).toLocaleString() : '-')
    },
    {
      title: 'End Time',
      dataIndex: 'endTime',
      key: 'endTime',
      render: (value: string | null) => (value ? new Date(value).toLocaleString() : '-')
    },
    {
      title: 'Duration',
      key: 'duration',
      render: (record: Session) => calcDuration(record.startTime, record.endTime)
    },
    {
      title: 'Room',
      key: 'room',
      render: (record: Session) => record.room?.title || record.roomId
    },
    {
      title: 'Actions',
      key: 'action',
      render: (record: Session) => (
        <Space>
          <Button
            size="small"
            icon={<EyeOutlined />}
            onClick={() => openDetails(record.id)}
          >
            Details
          </Button>
          <Popconfirm
            title="确认删除该会话？"
            okText="删除"
            cancelText="取消"
            onConfirm={() => handleDeleteSession(record.id)}
          >
            <Button
              size="small"
              danger
              icon={<DeleteOutlined />}
            />
          </Popconfirm>
        </Space>
      )
    }
  ], [sessions, openDetails, handleDeleteSession]);

  // 鍒囨崲tag鏄剧ず鐘舵€?
  const toggleTag = (tag: string) => {
    const newVisibleTags = new Set(visibleTags);
    if (newVisibleTags.has(tag)) {
      newVisibleTags.delete(tag);
    } else {
      newVisibleTags.add(tag);
    }
    setVisibleTags(newVisibleTags);
    setCurrentPage(1); // 重置分页
  };

  const handleRefreshDetails = async () => {
    if (!currentSessionId) return;
    setDetailsLoading(true);
    void loadGiftStats(currentSessionId);
    try {
      const details = await fetchSessionDetails(currentSessionId);
      setCurrentDetails(details);
      message.success('详情已刷新');
    } catch (e) {
      // 错误提示已在 hook 中处理
    } finally {
      setDetailsLoading(false);
    }
  };

  // 导出字幕（ASS）
  const handleExportSubtitles = () => {
    if (!currentSessionId) {
      message.error('请先选择一条会话');
      return;
    }
    const url = API_ENDPOINTS.SESSION_SUBTITLES_ASS(currentSessionId);
    window.open(url, '_blank');
  };

  const sessionStartTime = currentDetails?.session?.startTime;

  const timedMessages = useMemo(() => {
    if (!currentDetails?.messages) return [];
    
    return [...currentDetails.messages]
      .sort((a: any, b: any) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime())
      .filter((item: any) => item.messageType !== 'WebcastMemberMessage')
      .map((item: any) => {
        const createdAt = new Date(item.createdAt);
        const createdMs = createdAt.getTime();
        
        // 如果有视频真实开始时间，计算相对于视频开始的偏移量
        let offsetMs = 0;
        if (videoStartTime && !Number.isNaN(createdMs)) {
          // 使用更精确的时间计算
          const videoStartMs = videoStartTime.getTime();
          offsetMs = Math.max(0, createdMs - videoStartMs);
          
          // 添加时间校准：如果弹幕时间早于视频开始时间，设为0
          if (createdMs < videoStartMs) {
            offsetMs = 0;
          }
        } else if (sessionStartTime && !Number.isNaN(createdMs)) {
          // 回退到session开始时间（兼容没有视频时的情况）
          const startMs = new Date(sessionStartTime).getTime();
          offsetMs = Number.isNaN(startMs) ? 0 : Math.max(0, createdMs - startMs);
        }
        
        return {
          ...item,
          offsetMs,
          realTime: createdAt, // 添加真实时间戳
          // 添加精确的时间戳用于调试
          debugInfo: {
            createdMs,
            videoStartMs: videoStartTime?.getTime(),
            calculatedOffset: offsetMs
          }
        };
      });
  }, [currentDetails?.messages, sessionStartTime, videoStartTime]);

  const renderDanmakuRow = useCallback(({ index, style }: ListChildComponentProps) => {
    const item = visibleMessages[index];
    if (!item) {
      return null;
    }

    const displayName = item.userSnapshot?.userName || '未知用户';
    const payGrade = item.userSnapshot?.payGrade;
    const isAdmin = item.userSnapshot?.isAdmin;
    return (
      <div style={{ ...style, padding: `0 12px 6px`, boxSizing: 'border-box' }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8 }}>
          {showDanmakuAvatar && (
            <Avatar src={item.userSnapshot?.userAvatar ?? undefined} size="small">
              {displayName.charAt(0) || '?'}
            </Avatar>
          )}
          <div style={{ flex: 1, minWidth: 0 }}>
            <Space size={6} align="start">
              <Text strong style={{ whiteSpace: 'nowrap' }}>{displayName}</Text>
              {typeof payGrade === 'number' && payGrade > 0 && (
                <Tag color="gold">Lv.{payGrade}</Tag>
              )}
              {isAdmin && (
                <Tag color="red" style={{ fontWeight: 600 }}>管</Tag>
              )}
              <Tag color="blue">
                {item.realTime ? formatRealTime(item.realTime) : formatOffset(item.offsetMs)}
              </Tag>
            </Space>
            <div style={{ fontSize: 12, color: 'rgba(0,0,0,0.65)', marginTop: 4 }}>
              {item.content || '-'}
            </div>
          </div>
        </div>
      </div>
    );
  }, [visibleMessages]);

  const resetPlaybackState = () => {
    if (objectUrlRef.current) {
      URL.revokeObjectURL(objectUrlRef.current);
      objectUrlRef.current = null;
    }
    setVideoSource(null);
    setVideoLabel('');
    setUserUrl('');
    setCurrentTimeMs(-1);
    setVisibleMessages([]);
    setVideoStartTime(null);
    nextMessageIndexRef.current = 0;
    previousTimeRef.current = -1;
    if (videoRef.current) {
      videoRef.current.pause();
      videoRef.current.currentTime = 0;
    }
    setActiveTab('player');
    setGiftStats(null);
    setGiftStatsError(null);
  };

  useEffect(() => {
    resetPlaybackState();
  }, [currentSessionId]);

  useEffect(() => {
    return () => {
      if (objectUrlRef.current) {
        URL.revokeObjectURL(objectUrlRef.current);
        objectUrlRef.current = null;
      }
    };
  }, []);

  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;
    if (objectUrlRef.current) {
      URL.revokeObjectURL(objectUrlRef.current);
      objectUrlRef.current = null;
    }
    const objectUrl = URL.createObjectURL(file);
    objectUrlRef.current = objectUrl;
    setVideoSource(objectUrl);
    setVideoLabel(file.name);
    setUserUrl('');
    setCurrentTimeMs(-1);
    setVisibleMessages([]);
    nextMessageIndexRef.current = 0;
    previousTimeRef.current = -1;
    
    // 从文件名提取视频的真实开始时间
    const extractedTime = extractVideoStartTime(file.name);
    setVideoStartTime(extractedTime);
    if (extractedTime) {
      console.log('提取到视频开始时间:', extractedTime);
    } else {
      console.warn('无法从文件名提取时间:', file.name);
    }
    
    if (videoRef.current) {
      videoRef.current.load();
    }
    // 允许选择相同文件
    if (event.target) {
      event.target.value = '';
    }
  };

  const handleOpenFileDialog = () => {
    fileInputRef.current?.click();
  };

  const handleLoadUrl = () => {
    const trimmed = userUrl.trim();
    if (!trimmed) {
      message.warning('请输入有效的视频地址');
      return;
    }
    if (objectUrlRef.current) {
      URL.revokeObjectURL(objectUrlRef.current);
      objectUrlRef.current = null;
    }
    setVideoSource(trimmed);
    setVideoLabel(trimmed);
    setCurrentTimeMs(-1);
    setVisibleMessages([]);
    nextMessageIndexRef.current = 0;
    previousTimeRef.current = -1;
    
    // 从URL中的文件名提取视频的真实开始时间
    const filename = trimmed.split('/').pop() || trimmed;
    const extractedTime = extractVideoStartTime(filename);
    setVideoStartTime(extractedTime);
    if (extractedTime) {
      console.log('从URL提取到视频开始时间:', extractedTime);
    } else {
      console.warn('无法从URL文件名提取时间:', filename);
    }
    
    if (videoRef.current) {
      videoRef.current.load();
    }
  };

  const handleTimeUpdate = (event: React.SyntheticEvent<HTMLVideoElement>) => {
    const video = event.currentTarget;
    const currentSeconds = video.currentTime || 0;
    
    // 提高时间精度，保留小数点后3位（毫秒级精度）
    const preciseCurrentMs = Math.round(currentSeconds * 1000);
    
    // 添加时间偏移校正机制
    const correctedTimeMs = Math.max(0, preciseCurrentMs);
    
    setCurrentTimeMs(correctedTimeMs);
  };

  useEffect(() => {
    if (currentTimeMs < 0) {
      previousTimeRef.current = currentTimeMs;
      return;
    }
    
    // 自适应容错机制：根据消息密度和时间差动态调整
    const messageDensity = timedMessages.length > 0 ? timedMessages.length / Math.max(1, (timedMessages[timedMessages.length - 1]?.offsetMs || 1) / 1000) : 0;
    
    // 基础容错时间：消息密度高时使用更小的容错，密度低时使用更大的容错
    let tolerance = 100; // 默认100ms
    if (messageDensity > 10) { // 高密度：每秒超过10条消息
      tolerance = 50;
    } else if (messageDensity < 1) { // 低密度：每秒少于1条消息
      tolerance = 200;
    }
    
    // 考虑视频播放速度的影响
    const video = document.querySelector('video');
    const playbackRate = video?.playbackRate || 1;
    tolerance = Math.round(tolerance / playbackRate);
    
    if (timedMessages.length === 0) {
      if (visibleMessages.length !== 0) {
        setVisibleMessages([]);
      }
      nextMessageIndexRef.current = 0;
      previousTimeRef.current = currentTimeMs;
      return;
    }

    const lastVisibleOffset = visibleMessages.length > 0 ? visibleMessages[visibleMessages.length - 1].offsetMs : 0;
    
    // 改进时间跳跃检测逻辑
    const timeJumpThreshold = 2000; // 2秒的跳跃阈值
    const timeDiff = Math.abs(currentTimeMs - previousTimeRef.current);
    
    // 检测是否需要重置可见消息列表
    const needsReset = currentTimeMs + tolerance < lastVisibleOffset || 
                      timeDiff > timeJumpThreshold ||
                      (previousTimeRef.current > currentTimeMs && timeDiff > tolerance);
    
    if (needsReset) {
      // 重新计算可见消息，使用更精确的时间范围
      const timeWindow = tolerance * 2; // 双倍容错作为时间窗口
      const resetVisible = timedMessages.filter(item => {
        const inTimeWindow = item.offsetMs <= currentTimeMs + tolerance && 
                            item.offsetMs >= Math.max(0, currentTimeMs - timeWindow);
        return inTimeWindow;
      });
      
      setVisibleMessages(resetVisible);
      nextMessageIndexRef.current = resetVisible.length;
      previousTimeRef.current = currentTimeMs;
      return;
    }

    let idx = nextMessageIndexRef.current;
    const appended: any[] = [];
    
    // 使用更精确的时间窗口来添加消息
    // 只添加在当前时间点应该显示的新消息
    while (idx < timedMessages.length) {
      const message = timedMessages[idx];
      const messageTime = message.offsetMs;
      
      // 消息应该在当前时间显示
      if (messageTime <= currentTimeMs + tolerance) {
        // 确保消息不是太早的（避免重复添加）
        if (messageTime >= previousTimeRef.current - tolerance) {
          appended.push(message);
        }
        idx += 1;
      } else {
        // 后续消息都太晚了，停止检查
        break;
      }
    }
    
    if (appended.length > 0) {
      setVisibleMessages(prev => [...prev, ...appended]);
      nextMessageIndexRef.current = idx;
    }
    
    previousTimeRef.current = currentTimeMs;
  }, [currentTimeMs, timedMessages]);

  useEffect(() => {
    if (danmakuListRef.current && visibleMessages.length > 0) {
      danmakuListRef.current.scrollToItem(Math.max(visibleMessages.length - 1, 0), 'smart');
    }
  }, [visibleMessages]);

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ marginBottom: '16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div style={{ fontWeight: 600, fontSize: 16 }}>
          <HistoryOutlined style={{ marginRight: 8 }} /> 直播会话列表
        </div>
        <Space>
          <Form form={form} layout="inline">
            <Form.Item name="roomId" label="房间">
              <Select
                style={{ width: 240 }}
                placeholder="选择房间（留空为全部）"
                allowClear
                showSearch
                optionFilterProp="children"
                onChange={handleRoomChange}
              >
                {rooms.map(room => (
                  <Option key={room.id} value={room.id}>
                    {room.streamerName || room.title || room.id}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Form>
          <Button icon={<ReloadOutlined />} onClick={handleRefresh} loading={loading}>
            刷新
          </Button>
        </Space>
      </div>

      <Table
        columns={columns as any}
        dataSource={sessions}
        rowKey="id"
        loading={loading}
        pagination={{ pageSize: 20 }}
      />

      <Drawer
        title={
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span>详情</span>
            <Space>
              <Button size="small" icon={<ReloadOutlined />} onClick={handleRefreshDetails} loading={detailsLoading} disabled={!currentSessionId}>
                刷新
              </Button>
              <Button size="small" icon={<DownloadOutlined />} onClick={handleExportSubtitles} disabled={!currentSessionId}>
                导出字幕（ASS）
              </Button>
            </Space>
          </div>
        }
        placement="right"
        width={960}
        height="100vh"
        onClose={() => setDetailsOpen(false)}
        open={detailsOpen}
        bodyStyle={{ padding: '16px', display: 'flex', flexDirection: 'column', height: 'calc(100vh - 55px)' }}
      >
        {detailsLoading ? (
          <div>加载中...</div>
        ) : currentDetails ? (
          <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
            <div style={{ marginBottom: 16 }}>
              <Text type="secondary">房间：</Text>
              <Text strong>{currentDetails.session?.room?.title || currentDetails.session?.roomId}</Text>
            </div>

            <Tabs
              activeKey={activeTab}
              onChange={setActiveTab}
              items={[
                {
                  key: 'player',
                  label: '播放回放',
                  children: (
                      <div style={{ display: 'flex', gap: 16, height: '100%' }}>
                      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
                        <input
                          type="file"
                          accept="video/*"
                          ref={fileInputRef}
                          style={{ display: 'none' }}
                          onChange={handleFileSelect}
                        />
                        <Space style={{ marginBottom: 12 }} wrap>
                          <Button type="primary" onClick={handleOpenFileDialog}>
                            选择本地文件
                          </Button>
                          <Input
                            style={{ width: 260 }}
                            placeholder="输入远端视频地址"
                            value={userUrl}
                            onChange={e => setUserUrl(e.target.value)}
                            onPressEnter={handleLoadUrl}
                          />
                          <Button onClick={handleLoadUrl}>
                            加载地址
                          </Button>
                          {videoLabel && (
                            <Tag color="blue" style={{ marginLeft: 0 }}>
                              {videoLabel}
                            </Tag>
                          )}
                        </Space>
                        <div
                          ref={playerContainerRef}
                          style={{ height: '70vh', background: '#000', borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center' }}
                        >
                          {videoSource ? (
                            <video
                              ref={videoRef}
                              controls
                              style={{ width: '100%', maxHeight: '100%', borderRadius: 8 }}
                              src={videoSource}
                              onTimeUpdate={handleTimeUpdate}
                            >
                              当前浏览器不支持该视频格式                            </video>
                          ) : (
                            <Text type="secondary">请选择本地文件或输入视频地址进行播放</Text>
                          )}
                        </div>
                      </div>
                      <Divider type="vertical" style={{ height: '100%' }} />
                      <div style={{ width: 360, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
                          <Text strong>弹幕回放 ({visibleMessages.length}/{timedMessages.length})</Text>
                          <Space size={8}>
                            <span style={{ fontSize: 12, color: 'rgba(0,0,0,0.45)' }}>显示头像</span>
                            <Switch
                              size="small"
                              checked={showDanmakuAvatar}
                              onChange={setShowDanmakuAvatar}
                            />
                          </Space>
                        </div>
                        <div style={{ height: '70vh', border: '1px solid #f0f0f0', borderRadius: 8, padding: '0 12px 8px', background: '#fafafa' }}>
                          {visibleMessages.length === 0 ? (
                            <div style={{ padding: '0 12px' }}>
                              <Text type="secondary">播放进度达到对应时间后将自动出现弹幕</Text>
                            </div>
                          ) : (
                            <VirtualList
                              ref={danmakuListRef}
                              height={Math.floor(windowHeight * 0.7) - 20}
                              itemCount={visibleMessages.length}
                          itemSize={DANMAKU_ITEM_HEIGHT}
                          width="100%"
                              itemKey={(index: number) => visibleMessages[index]?.id ?? `${visibleMessages[index]?.createdAt ?? index}-${index}`}
                            >
                              {renderDanmakuRow}
                            </VirtualList>
                          )}
                        </div>
                      </div>
                    </div>
                  ),
                },
                {
                  key: 'logs',
                  label: '弹幕 / 礼物列表',
                  children: (
                    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
                      <div style={{ marginBottom: 16 }}>
                        <Text strong>礼物统计</Text>
                        <div style={{ marginTop: 8, background: '#fafafa', border: '1px solid #f0f0f0', borderRadius: 8, padding: '12px 16px' }}>
                          {giftStatsLoading ? (
                            <Spin size="small" />
                          ) : giftStatsError ? (
                            <Text type="danger">{giftStatsError}</Text>
                          ) : giftStats ? (
                            <div>
                              <Space size={32} wrap align="start">
                                <div>
                                  <Text type="secondary">礼物总数</Text>
                                  <div style={{ fontSize: 20, fontWeight: 600 }}>{giftStats.totalQuantity}</div>
                                </div>
                                <div>
                                  <Text type="secondary">礼物种类</Text>
                                  <div style={{ fontSize: 20, fontWeight: 600 }}>{giftStats.totalGiftTypes}</div>
                                </div>
                                <div>
                                  <Text type="secondary">礼物音浪</Text>
                                  <div style={{ fontSize: 20, fontWeight: 600 }}>{giftStats.totalSoundWave}</div>
                                </div>
                                <div>
                                  <Text type="secondary">送礼用户数</Text>
                                  <div style={{ fontSize: 20, fontWeight: 600 }}>{giftStats.uniqueUsers}</div>
                                </div>
                              </Space>
                              <div style={{ marginTop: 12 }}>
                                {giftStats.breakdown.length > 0 ? (
                                  <div>
                                    <Text type="secondary">Top 礼物</Text>
                                    <List
                                      size="small"
                                      style={{ marginTop: 8 }}
                                      dataSource={giftStats.breakdown.slice(0, 5)}
                                      renderItem={item => (
                                        <List.Item>
                                          <List.Item.Meta
                                            avatar={
                                              item.icon ? (
                                                <Avatar src={item.icon ?? undefined} size="small" />
                                              ) : (
                                                <Avatar size="small">{item.name ? item.name.charAt(0) : '?'}</Avatar>
                                              )
                                            }
                                            title={
                                              <Space size={12} wrap>
                                                <Text strong>{item.name}</Text>
                                                <Tag color="blue">x{item.quantity}</Tag>
                                                <Tag color="orange">{item.amount} 音浪</Tag>
                                              </Space>
                                            }
                                            description={item.price !== undefined && item.price !== null ? `单价 ${item.price}` : '单价未知'}
                                          />
                                        </List.Item>
                                      )}
                                    />
                                  </div>
                                ) : (
                                  <Text type="secondary">本场暂无礼物记录</Text>
                                )}
                              </div>
                            </div>
                          ) : (
                            <Text type="secondary">暂无礼物数据</Text>
                          )}
                        </div>
                      </div>
                      <Divider orientation="left">
                        <MessageOutlined /> 消息和礼物记录({(currentDetails.messages?.length || 0) + (currentDetails.giftRecords?.length || 0)})
                      </Divider>
                      {(() => {
                        const allData = [
                          ...(currentDetails.messages || []).map((item: any) => ({ ...item, type: 'message' })),
                          ...(currentDetails.giftRecords || []).map((item: any) => ({ ...item, type: 'gift' }))
                        ].sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());

                        const allTags = new Set<string>();
                        allData.forEach(item => {
                          if (item.type === 'message') {
                            const tag = item.messageType?.replace('Webcast', '').replace('Message', '') || '消息';
                            allTags.add(tag);
                          } else {
                            const tag = item.gift?.name || '礼物';
                            allTags.add(tag);
                          }
                        });

                        const filteredData = visibleTags.size === 0 ? allData : allData.filter(item => {
                          const tag = item.type === 'message'
                            ? (item.messageType?.replace('Webcast', '').replace('Message', '') || '消息')
                            : (item.gift?.name || '礼物');
                          return visibleTags.has(tag);
                        });

                        const startIndex = (currentPage - 1) * pageSize;
                        const endIndex = startIndex + pageSize;
                        const paginatedData = filteredData.slice(startIndex, endIndex);

                        return (
                          <div style={{ display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0 }}>
                            <div style={{ marginBottom: 16 }}>
                              <div style={{ marginBottom: 12 }}>
                                <Text strong>标签过滤：</Text>
                                <div style={{ marginTop: 8 }}>
                                  {Array.from(allTags).map(tag => {
                                    const isVisible = visibleTags.has(tag);
                                    const count = allData.filter(item => {
                                      const itemTag = item.type === 'message'
                                        ? (item.messageType?.replace('Webcast', '').replace('Message', '') || '消息')
                                        : (item.gift?.name || '礼物');
                                      return itemTag === tag;
                                    }).length;

                                    return (
                                      <Tag
                                        key={tag}
                                        color={isVisible ? 'blue' : 'default'}
                                        style={{ cursor: 'pointer', margin: 2, opacity: isVisible ? 1 : 0.6 }}
                                        onClick={() => toggleTag(tag)}
                                      >
                                        {tag} ({count})
                                      </Tag>
                                    );
                                  })}
                                  {visibleTags.size > 0 && (
                                    <Button
                                      size="small"
                                      type="link"
                                      onClick={() => {
                                        setVisibleTags(new Set());
                                        setCurrentPage(1);
                                      }}
                                    >
                                      清除过滤
                                    </Button>
                                  )}
                                </div>
                              </div>
                              <div style={{ textAlign: 'right' }}>
                                <Text type="secondary">
                                  {visibleTags.size > 0 ? `已过滤 ${filteredData.length} 条` : `共 ${allData.length} 条`}记录，当前显示第 {startIndex + 1}-{Math.min(endIndex, filteredData.length)} 条                                </Text>
                              </div>
                            </div>

                            <div style={{ flex: 1, overflow: 'auto', marginBottom: 16 }}>
                              <List
                                size="small"
                                dataSource={paginatedData}
                                renderItem={(item: any) => (
                                  <List.Item>
                                    <List.Item.Meta
                                      avatar={
                                        <Avatar src={item.userSnapshot?.userAvatar} size="small">
                                          {item.userSnapshot?.userName?.charAt(0) || '?'}
                                        </Avatar>
                                      }
                                      title={
                                        <Space>
                                          <Text strong>{item.userSnapshot?.userName || '未知鐢ㄦ埛'}</Text>
                                          {item.type === 'message' ? (
                                            <Tag color="blue" icon={<MessageOutlined />}>
                                              {item.messageType?.replace('Webcast', '').replace('Message', '') || '消息'}
                                            </Tag>
                                          ) : (
                                            <Tag color="gold" icon={<GiftOutlined />}>
                                              {item.gift?.name || '礼物'}
                                            </Tag>
                                          )}
                                          {item.type === 'gift' && (
                                            <Text type="secondary">x{item.quantity}</Text>
                                          )}
                                          <Text type="secondary" style={{ fontSize: 12 }}>
                                            {new Date(item.createdAt).toLocaleString()}
                                          </Text>
                                        </Space>
                                      }
                                      description={
                                        item.type === 'message'
                                          ? (item.content || '-')
                                          : `总额 ${(item.gift?.price || 0) * item.quantity} 金币`
                                      }
                                    />
                                  </List.Item>
                                )}
                              />
                            </div>

                            <div
                              style={{
                                borderTop: '1px solid #f0f0f0',
                                paddingTop: 16,
                                textAlign: 'center',
                                background: '#fff',
                              }}
                            >
                              <Pagination
                                current={currentPage}
                                pageSize={pageSize}
                                total={filteredData.length}
                                showSizeChanger
                                showQuickJumper
                                showTotal={(total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`}
                                pageSizeOptions={['20', '50', '100', '200']}
                                onChange={(page, size) => {
                                  setCurrentPage(page);
                                  if (size !== pageSize) {
                                    setPageSize(size);
                                    setCurrentPage(1);
                                  }
                                }}
                              />
                            </div>
                          </div>
                        );
                      })()}
                    </div>
                  ),
                },
              ]}
            />
          </div>
        ) : (
          <div>请选择一条会话查看详情</div>
        )}
      </Drawer>
    </div>
  );
};

export default SessionsPage;










